package cs3343.project.family;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.HashMap;

import javax.swing.ImageIcon;
import javax.swing.JOptionPane;

/**
 * The Class ProfileManager.
 */
public class ProfileManager {
	
	
	/** The profiles. */
	public static HashMap<String, Character> profiles = new HashMap<String, Character>();
	
	/** The profile arr. */
	public static String[] profileArr;

	/**
	 * Profile file exist.
	 *
	 * @param filePath the file path
	 * @return true, if successful
	 */
	public static boolean profileFileExist(String filePath) {
			File file = new File(filePath);
			if (file.exists())
				return true; 
			return false;
	}	
	
	/**
	 * Creates the new profile.
	 *
	 * @param name the name
	 */
	public static void createNewProfile(String name) {
		if (profileNameExist(name) == false) {
			int newID = countExistNumOfProfile() + 1;
			try	{
				BufferedWriter outfile = new BufferedWriter(new OutputStreamWriter(
						new FileOutputStream(ConfigManager.PROFILE_PATH, true), "UTF-8"));
				outfile.newLine();
				outfile.append(String.valueOf(newID) + "\t" + name + "\t0");
				outfile.close();
			}
			catch (IOException e) {
				ConfigManager.saveErrorLog(e.toString());
			}
		}
		else {
			JOptionPane.showMessageDialog (null, "This profile is already created.", "Profile existed", JOptionPane.ERROR_MESSAGE);
		}
	}
	
	/**
	 * Read from profile.
	 */
	public static void readFromProfile() {
		if (!profiles.isEmpty())
			profiles.clear();
		
		String result[];
		try {
	        BufferedReader infile = new BufferedReader(new InputStreamReader(
	        		new FileInputStream(ConfigManager.PROFILE_PATH), "UTF-8"));
	        String str;
	        
	        while ((str = infile.readLine()) != null) 
	        {
	        	if (str.length() > 0) {
                    // UTF - 8 BOM CHAR
                    int c = str.charAt(0);
                    if (c == 65279)
                    	str = str.substring(1, str.length());
	        	}
	            result = str.split("\t");

	            String proimgPath = ConfigManager.IMAGE_PATH + "profilePic" + result[0] + ".jpg";
	            String gproimgPath = ConfigManager.IMAGE_PATH + "gprofilePic" + result[0] + ".jpg";
	            String iconimgPath = ConfigManager.IMAGE_PATH + "char" + result[0] + ".jpg";
	            
	            Character player = new Character(result[1], new ImageIcon(proimgPath), new ImageIcon(gproimgPath), new ImageIcon(iconimgPath));
	            profiles.put(result[0], player);
	        }
	        infile.close();
	        generateProfileArray();
	    } 
	    catch (IOException e) {
	    	ConfigManager.saveErrorLog(e.toString());
	    }
	}
	
	/**
	 * Generate profile array.
	 */
	private static void generateProfileArray() {
		profileArr = new String[profiles.size() + 1];
		profileArr[0] = ConfigManager.getLangString("comboChooseProfile");
		
		for (int i = 1; i < profiles.size() + 1; i++) {
			profileArr[i] = profiles.get(String.valueOf(i)).getName();
		}
	}
	
	/**
	 * Update profile.
	 *
	 * @param player the player
	 */
	public static void updateProfile(Character player) {
		String result[];
		int id = 0;
		try {
	        BufferedReader infile = new BufferedReader(new InputStreamReader(
	        		new FileInputStream(ConfigManager.PROFILE_PATH), "UTF-8"));
	        String str;
	        
	        while ((str = infile.readLine()) != null) 
	        {
	        	if (str.length() > 0) {
                    // UTF - 8 BOM CHAR
                    int c = str.charAt(0);
                    if (c == 65279)
                    	str = str.substring(1, str.length());
	        	}
	        	
	            result = str.split("\t");
	            if (result[1].equalsIgnoreCase(player.getName())) {
	            	id = Integer.parseInt(result[0]);
	            }
	            Character temp = new Character(result[1], Integer.parseInt(result[2]));
	            profiles.put(result[0], temp);	 
	        }
	        infile.close();
	        
	        BufferedWriter outfile = new BufferedWriter(new OutputStreamWriter(
					new FileOutputStream(ConfigManager.PROFILE_PATH, false), "UTF-8"));
			int counter = 0;
			while (counter++ < profiles.size()) {
				if (counter != id)
					outfile.append(String.valueOf(counter) + "\t" + profiles.get(String.valueOf(counter)).getName() + "\t" + profiles.get(String.valueOf(counter)).getEsteem());
				else
					outfile.append(String.valueOf(counter) + "\t" + profiles.get(String.valueOf(counter)).getName() + "\t" + (profiles.get(String.valueOf(counter)).getEsteem() + player.getEsteem()));
				outfile.newLine();
			}
			outfile.close();
	    }
	    catch (IOException e) {
	    	ConfigManager.saveErrorLog(e.toString());
	    }
	}
	
	/**
	 * Gets the profile size.
	 *
	 * @return the profile size
	 */
	public static int getProfileSize() {
		return profiles.size();
	}
	
	/**
	 * Gets the profile array.
	 *
	 * @return the profile array
	 */
	public static String[] getProfileArray() {
		String[] profileArr = new String[profiles.size()];
		for (int i = 0; i < profileArr.length; i++) {
			profileArr[i] = profiles.get(String.valueOf(i)).getName();
		}
		return profileArr;
	}
	
	/**
	 * Count exist num of profile.
	 *
	 * @return the int
	 */
	private static int countExistNumOfProfile() {
		int count = 0;
		try {
			BufferedReader infile = new BufferedReader(new InputStreamReader(
					new FileInputStream(ConfigManager.PROFILE_PATH), "UTF-8"));
	        String str;
	        
	        while ((str = infile.readLine()) != null) 
	        {
	        	if (str.length() > 0) {
                    // UTF - 8 BOM CHAR
                    int c = str.charAt(0);
                    if (c == 65279)
                    	str = str.substring(1, str.length());
	        	}
	        	count++;
	        }
	        infile.close();
	    } 
	    catch (IOException e) {
	    	ConfigManager.saveErrorLog(e.toString());
	    }
		return count;
	}
	
	/**
	 * Profile name exist.
	 *
	 * @param name the name
	 * @return true, if successful
	 */
	private static boolean profileNameExist(String name) {
		String result[];
		try {
			BufferedReader infile = new BufferedReader(new InputStreamReader(
					new FileInputStream(ConfigManager.PROFILE_PATH), "UTF-8"));
	        String str;
	        
	        while ((str = infile.readLine()) != null) 
	        {
	        	if (str.length() > 0) {
                    // UTF - 8 BOM CHAR
                    int c = str.charAt(0);
                    if (c == 65279)
                    	str = str.substring(1, str.length());
	        	}
	        	result = str.split("\t");
	        	if (result[1].equalsIgnoreCase(name))
	        		return true;
	        }
	        infile.close();
	    } 
	    catch (IOException e) {
	    	ConfigManager.saveErrorLog(e.toString());
	    }
		return false;
	}
}
